// 生成基于时间戳和当天序号的检测单编号
async function generateDetectionNo(detectTime, vk, db, _, excludeId = null) {
	// 解析检测时间
	let date = new Date(detectTime);
	let year = date.getFullYear();
	let month = String(date.getMonth() + 1).padStart(2, '0');
	let day = String(date.getDate()).padStart(2, '0');
	let hour = String(date.getHours()).padStart(2, '0');
	let minute = String(date.getMinutes()).padStart(2, '0');

	// 生成时间戳前缀 yyyyMMddHHmm (12位)
	let timePrefix = `${year}${month}${day}${hour}${minute}`;

	// 获取当天的开始和结束时间戳
	let dayStart = new Date(year, date.getMonth(), day, 0, 0, 0).getTime();
	let dayEnd = new Date(year, date.getMonth(), day, 23, 59, 59, 999).getTime();

	// 构建查询条件，基于detect_time字段查询当天的记录
	let whereJson = {
		detect_time: _.gte(dayStart).and(_.lte(dayEnd))
	};

	// 如果是更新操作，排除当前记录
	if (excludeId) {
		whereJson._id = _.neq(excludeId);
	}

	// 查询当天已有的检测单数量，基于detect_time字段
	let count = await vk.baseDao.count({
		dbName: "tm-detection-form",
		whereJson: whereJson
	});

	// 生成序号，从1开始，补齐到5位 (总长度17位: 12位时间戳 + 5位序号)
	let sequence = count + 1;
	let sequenceStr = String(sequence).padStart(5, '0');

	return timePrefix + sequenceStr;
}

module.exports = {
	/**
	 * 修改数据
	 * @url admin/kong/sys/update 前端调用的url参数地址
	 * data 请求参数 说明
	 * res 返回参数说明
	 * @param {Number} code 错误码，0表示成功
	 * @param {String} msg 详细信息
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: 'ok' };
		// 业务逻辑开始-----------------------------------------------------------
		let { _id, client, client_name, detection_type, submitUser, detection_category, detection_standard,addressps, detection_standard_name, detection_user, detect_time, address, sample_id, sampleno, samplename, sample_save_info, sample_keeptime, sample_troptime, sample_list, submituser_address, contact, contact_number, sale_for, remark } = data;
		// 这里需要把 params1 params2 params3 改成你数据库里允许用户添加的字段
		if (vk.pubfn.isNullOne(_id)) {
			return { code: -1, msg: '参数错误' };
		}
		let dbName = "tm-detection-form";
		let info = await vk.baseDao.findByWhereJson({
			dbName: "uni-id-users",
			whereJson: {
				nickname: detection_user,
			}
		}),
			_client_price = await vk.baseDao.findByWhereJson({
				dbName: "tm-client-price",
				whereJson: {
					client_id: client,
					category_id: detection_category
				}
			}),
			_price = 0,
			detection_user_sign = undefined;
		if (vk.pubfn.isNotNull(info) && vk.pubfn.isNotNull(info.sign_image)) {
			detection_user_sign = info.sign_image
		}

		// 获取原有的检测单信息，检查是否需要重新生成编号
		let originalRecord = await vk.baseDao.findById({
			dbName,
			id: _id
		});

		let updateData = {
			client,
			client_name,
			detection_type,
			submitUser,
			detection_category,
			detection_standard,
			detection_standard_name,
			detection_user,
			detect_time,
			address,
			sample_id,
			sampleno,
			samplename,
			sample_save_info,
			sample_keeptime,
			sample_troptime,
			submituser_address,
			addressps,
			contact,
			contact_number,
			sale_for,
			remark,
			detection_user_sign: detection_user_sign
		};

		// 如果检测时间发生变化，重新生成编号
		if (originalRecord && originalRecord.detect_time) {
			let originalDate = new Date(originalRecord.detect_time);
			let newDate = new Date(detect_time);

			// 比较日期是否不同（只比较年月日）
			if (originalDate.getFullYear() !== newDate.getFullYear() ||
				originalDate.getMonth() !== newDate.getMonth() ||
				originalDate.getDate() !== newDate.getDate()) {
				// 重新生成编号，排除当前记录
				updateData.no = await generateDetectionNo(detect_time, vk, db, _, _id);
			}
		}

		await vk.baseDao.updateById({
            dbName,
            id: _id,
            dataJson: updateData
        });

		let _dels = sample_list.filter(x => x.isdel).map(x => x._id)
		await vk.baseDao.del({
			dbName: "tm-sample-testing",
			whereJson: {
				_id: _.in(_dels)
			}
		});
		if (sample_list.length > 0) {
			if (vk.pubfn.isNotNull(_client_price) && vk.pubfn.isNotNull(_client_price.price))
				_price = vk.pubfn.string2Number(_client_price.price);
			let _add_sample_list = sample_list.filter(x => vk.pubfn.isNull(x._id)).map(x => {
				return {
					'detectionform_id': _id,
					'client': client,
					'client_name': client_name,
					...x
				}
			})
			if (vk.pubfn.isNotNull(_add_sample_list)) {
				await vk.baseDao.adds({
					dbName: "tm-sample-testing",// 表名
					dataJson: _add_sample_list
				});
			}

		}
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}

}
